<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :queryAuth="false"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="sqlsh" label="申请流水号">
          <FIInput v-model="state.query.sqlsh" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="mfmc" label="卖方名称">
          <FIInput v-model="state.query.mfmc" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="gnblchtdm" label="国内保理池合同代码">
          <FIInput v-model="state.query.gnblchtdm" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="gnblchtbm" label="国内保理池合同编码">
          <FIInput v-model="state.query.gnblchtbm" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="ywpz" label="业务品种">
          <FISelect v-if="arr2.length > 0" v-model="state.query.ywpz" valueCustom="value" :options="arr2" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="sqzt" label="申请状态">
          <FISelect v-if="arr2.length > 0" v-model="state.query.sqzt" valueCustom="value" :options="arr2" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="cjr" label="创建人">
          <FISelect v-if="arr2.length > 0" v-model="state.query.cjr" valueCustom="value" :options="arr2" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="cjrssjg" label="创建人所属机构">
          <FISelect
            v-if="arr2.length > 0"
            v-model="state.query.cjrssjg"
            valueCustom="value"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="codesetId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      checkMode="radio"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :settingConfig="{ hidden: true }"
      :showSaveModel="false"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
    >
      <template #headerBtn>
        <FIButton border>新增</FIButton>
        <FIPopconfirmBtn
          class="margin-left12"
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
          :isVisible="!!checkedRows.length"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template>
    </FITable>
    <!-- <FIModel v-model="isVisible" title="明细设置">
      <InfoForm :node-info="selectedRow"></InfoForm>
  </FIModel> -->
    <assign-post
      ref="childComponent"
      :postShow="postShow"
      @update:postShow="(newValue) => (postShow = newValue)"
      :editData="selectedRow"
      @refresh="refreshTable"
    ></assign-post>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import assignPost from './assignPost.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiGetbackproject } from '@/api/configEnvMaint/index.ts'
const route = useRoute()
const isVisible = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
const childComponent = ref(null)
const postShow = ref(false)
// 页面编码
const tableId = 'receivablesMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const selectedRow = ref({})
const state = reactive({
  query: {
    sqlsh: '',
    mfmc: '',
    gnblchtdm: '',
    gnblchtbm: '',
    ywpz: '',
    sqzt: '',
    cjr: '',
    cjrssjg: '',
    current: 1,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '申请流水号',
    prop: 'codesetCode',
    align: 'center',
    width: '180',
  },
  {
    label: '卖方名称',
    prop: 'codesetName',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '180',
  },
  {
    label: '国内保理合同代码',
    prop: 'remark',
    align: 'center',
    width: '180',
  },
  {
    label: '国内保理合同编号',
    prop: 'projectName',
    align: 'center',
    width: '180',
  },
  {
    label: '本次转让笔数',
    prop: 'recCreator',
    align: 'center',
    width: '120',
  },
  {
    label: '本次转让总净额(元)',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
  },
  {
    label: '申请状态',
    prop: 'recRevisare',
    align: 'center',
    width: '120',
  },
  {
    label: '流程阶段',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      { label: '明细', type: 'detail' },
      { label: '启用', type: 'enable' },
    ],
  },
])
// 操作列回调
const handleAction = (item, rowData) => {
  if (item.type === 'detail') {
    postShow.value = true
    selectedRow.value = rowData
  }
}
const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const refreshTable = () => {
  pageConfig.currentPage = 1
  searchFn()
}
// 查询接口
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiRequestPost('/rm2/codesetMaint/queryCodeset', state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// 新增insert，编辑update 操作
const handleSave = (row) => {
  isTableLoading.value = true
  apiRequestPost('/rm2/xxx', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        searchFn()
        useMessage().success('更新成功')
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
// 删除
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.id) ids.push(item?.id)
    })
  isTableLoading.value = true
  apiRequestPost('/rm2/xxx/xxxx', ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success('删除成功')
      }
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)
// 如果使用table，底部的保存按钮功能，则使用这个回调方法
const addRowSave = (data) => {
  handleSave(data, 'add')
}
watch(
  () => columns.values,
  (newValue) => {},
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
const arr2 = ref([])
const getProjectname = () => {
  apiGetbackproject().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `【${item.projectCname}】${item.projectEname}`
          item.value = item.projectEname
        })
      if (Array.isArray(res.data.data)) {
        arr2.value = res.data.data
        console.log(arr2.value)
      }
    }
  })
}
onMounted(() => {
  getProjectname()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
